<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElRow, ElCol, ElButton, ElDialog, ElMessage, ElTabs, ElTabPane } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import AccountCard from '@/components/AccountCard/index.vue'
import StatusCard from '@/components/StatusCard/index.vue'
import DataTable from '@/components/DataTable/index.vue'
import type { SocialAccount } from '@/types'
import { getAccounts } from '@/utils/api'

const activeTab = ref('cards')
const accounts = ref<SocialAccount[]>([])
const loading = ref(false)
const showAddDialog = ref(false)

const accountStats = reactive({
  total: 0,
  active: 0,
  inactive: 0,
  suspended: 0
})

const tableColumns = [
  { key: 'username', label: '用户名', sortable: true },
  { key: 'platform', label: '平台', sortable: true },
  { key: 'status', label: '状态', sortable: true },
  { key: 'followers', label: '粉丝数', sortable: true, formatter: (row: SocialAccount) => row.followers?.toLocaleString() || '0' },
  { key: 'posts', label: '作品数', sortable: true, formatter: (row: SocialAccount) => row.posts?.toLocaleString() || '0' },
  { key: 'lastLogin', label: '最后登录', sortable: true, formatter: (row: SocialAccount) => row.lastLogin ? new Date(row.lastLogin).toLocaleDateString() : '未知' }
]

onMounted(() => {
  loadAccounts()
})

const loadAccounts = async() => {
  loading.value = true
  try {
    const response = await getAccounts()
    accounts.value = response.data || []
    updateStats()
  } catch (error) {
    ElMessage.error('加载账号列表失败')
    accounts.value = [
      {
        id: '1',
        username: 'test_user_001',
        platform: 'tiktok',
        status: 'active',
        followers: 15420,
        following: 234,
        posts: 67,
        lastLogin: Date.now() - 86400000,
        createdAt: Date.now() - 86400000 * 30
      },
      {
        id: '2',
        username: 'social_demo',
        platform: 'instagram',
        status: 'inactive',
        followers: 8932,
        following: 445,
        posts: 123,
        lastLogin: Date.now() - 86400000 * 7,
        createdAt: Date.now() - 86400000 * 45
      }
    ]
    updateStats()
  } finally {
    loading.value = false
  }
}

const updateStats = () => {
  accountStats.total = accounts.value.length
  accountStats.active = accounts.value.filter(acc => acc.status === 'active').length
  accountStats.inactive = accounts.value.filter(acc => acc.status === 'inactive').length
  accountStats.suspended = accounts.value.filter(acc => acc.status === 'suspended').length
}

const handleEdit = (account: SocialAccount) => {
  ElMessage.info(`编辑账号: ${account.username}`)
}

const handleDelete = async(account: SocialAccount) => {
  try {
    await deleteAccount(account.id)
    await loadAccounts()
    ElMessage.success(`账号 ${account.username} 删除成功`)
  } catch (error) {
    ElMessage.error(`删除账号失败: ${error}`)
  }
}

const handleLogin = async(account: SocialAccount) => {
  try {
    ElMessage.info(`正在登录账号: ${account.username}`)
  } catch (error) {
    ElMessage.error(`登录失败: ${error}`)
  }
}

const handleLogout = async(account: SocialAccount) => {
  try {
    ElMessage.info(`正在登出账号: ${account.username}`)
  } catch (error) {
    ElMessage.error(`登出失败: ${error}`)
  }
}

const handleManage = (account: SocialAccount) => {
  ElMessage.info(`管理账号: ${account.username}`)
}

const handleAddAccount = () => {
  showAddDialog.value = true
}

const handleRefresh = () => {
  loadAccounts()
}

const handleRowClick = (account: SocialAccount) => {
  handleManage(account)
}
</script>

<template>
  <div class="accounts-page">
    <div class="page-header">
      <h2>账号管理</h2>
      <div class="header-actions">
        <ElButton :icon="Refresh" @click="handleRefresh">刷新</ElButton>
        <ElButton type="primary" :icon="Plus" @click="handleAddAccount">
          添加账号
        </ElButton>
      </div>
    </div>

    <!-- 账号统计 -->
    <ElRow :gutter="20" class="stats-row">
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="账号总数"
          :value="accountStats.total"
          color="#409eff"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="活跃账号"
          :value="accountStats.active"
          color="#67c23a"
          trend="up"
          :trend-value="`${Math.round((accountStats.active / Math.max(accountStats.total, 1)) * 100)}%`"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="未激活"
          :value="accountStats.inactive"
          color="#e6a23c"
          trend="neutral"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="已暂停"
          :value="accountStats.suspended"
          color="#f56c6c"
          trend="down"
        />
      </ElCol>
    </ElRow>

    <!-- 账号列表 -->
    <ElTabs v-model="activeTab" class="accounts-tabs">
      <ElTabPane label="卡片视图" name="cards">
        <div class="accounts-grid">
          <ElRow :gutter="20">
            <ElCol
              v-for="account in accounts"
              :key="account.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="account-col"
            >
              <AccountCard
                :account="account"
                @edit="handleEdit"
                @delete="handleDelete"
                @login="handleLogin"
                @logout="handleLogout"
                @manage="handleManage"
              />
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>

      <ElTabPane label="列表视图" name="table">
        <DataTable
          :data="accounts"
          :columns="tableColumns"
          :loading="loading"
          :total="accounts.length"
          show-search
          show-refresh
          show-add
          add-text="添加账号"
          search-placeholder="搜索账号..."
          @refresh="handleRefresh"
          @add="handleAddAccount"
          @row-click="handleRowClick"
        />
      </ElTabPane>
    </ElTabs>

    <!-- 添加账号对话框 -->
    <ElDialog
      v-model="showAddDialog"
      title="添加社交账号"
      width="600px"
      :before-close="() => showAddDialog = false"
    >
      <div class="add-account-form">
        <p>账号添加功能正在开发中...</p>
        <p>支持的平台：</p>
        <ul>
          <li>TikTok - 短视频平台</li>
          <li>Instagram - 图片社交</li>
          <li>Facebook - 社交网络</li>
          <li>Twitter - 微博社交</li>
          <li>YouTube - 视频平台</li>
          <li>LinkedIn - 职业网络</li>
        </ul>
      </div>
      
      <template #footer>
        <ElButton @click="showAddDialog = false">取消</ElButton>
        <ElButton type="primary" @click="showAddDialog = false">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.accounts-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h2 {
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-row {
    margin-bottom: 24px;
  }
  
  .accounts-tabs {
    .accounts-grid {
      .account-col {
        margin-bottom: 20px;
      }
    }
  }
  
  .add-account-form {
    padding: 20px 0;
    
    ul {
      margin: 16px 0;
      padding-left: 24px;
      
      li {
        margin-bottom: 8px;
        color: var(--el-text-color-regular);
      }
    }
  }
}

@media (max-width: 768px) {
  .accounts-page {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h2 {
        text-align: center;
      }
      
      .header-actions {
        justify-content: center;
      }
    }
  }
}
</style>